
package scrum.gui;


import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.tree.*;
import java.awt.Dimension;
import java.io.IOException;

import javax.xml.bind.JAXBException;
import scrum.entity.*;
import scrum.gui.project.*;
import scrum.gui.help.*;
import scrum.xmlDatabase.*;


public class MainFrame extends JFrame {
    
    
	private static final long serialVersionUID = 1L;
	private GeneralPane generalTabPane;
  //  private EmployeePane employeeTabPane;
    private DefaultMutableTreeNode rootTreeNode;
    protected DefaultTreeModel treeModel;
    private ProjectXMLConnector xmlConnector;
    ProjectsStore projectStore;
    Project currentProject = new Project();
  
    
   
 
    /** Creates new form gui */
    public MainFrame() {
    	
    	
    	initComponents();
        //connect to the XML base
        xmlConnector = new ProjectXMLConnector();
        readXML();
        if(!projectStore.getProjectsList().isEmpty()) {
        	
        	currentProject = projectStore.getProjectsList().get(0);
        	
        	
        }else{
        	
        	currentProject = new Project();
        	this.jButtonOpenProject.setEnabled(false);
        	this.jButtonDeleteProject.setEnabled(false);
        	this.MenuItemOpen.setEnabled(false);
        	this.MenuItemDelete.setEnabled(false);
        	
        }
        createNodes(rootTreeNode);
        treeModel.reload();
        generalTabPane.setCurrentProject(currentProject);
        setModifyMode(false);
        showProject(); 
    }
    
    private void readXML(){
    	
    	try {
			projectStore = xmlConnector.readFromXML();	
		} catch (JAXBException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
    }
    
    private void writeXML(){
    	try {
    		xmlConnector.setProjectList(projectStore.getProjectsList());
			xmlConnector.writeToXML();
		} catch (JAXBException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
    }
    
   
    
    //Create a project
     private void createNewProject() {
     	
    	 currentProject = new Project();
    	 generalTabPane.setCurrentProject(currentProject);
    	 generalTabPane.clearProject();
    	 generalTabPane.setModifyMode(true);
    	 generalTabPane.setDate();
         statusBar.setText("Create Project Ready");
     }
     
     //Open a project
     private void openProject() {
     	
     	generalTabPane.setModifyMode(true);
        statusBar.setText("Open project Ready,modify");
     }
     
     private void closeProject(){
    	 
    	 int index= getIndex(currentProject);
    	
    	 if(index == -1){
    		 index = 0;
    	 }
    	 readXML();
    	 if(!projectStore.getProjectsList().isEmpty()) {
         	
         	currentProject = projectStore.getProjectsList().get(index);
         	
         }else{
        	
         	currentProject = new Project();
        	this.jButtonOpenProject.setEnabled(false);
        	this.jButtonDeleteProject.setEnabled(false);
        	this.MenuItemOpen.setEnabled(false);
        	this.MenuItemDelete.setEnabled(false);
         }
    	 generalTabPane.setCurrentProject(currentProject);
         setModifyMode(false);
         
         showProject(); 
    	
     }
     
     
     private void deleteProject() {
    	 
		int n = JOptionPane.showConfirmDialog(this,
				"Do you want to delete this project", "Question",
				JOptionPane.YES_NO_OPTION);
		if (n == 0) {
			removeCurrentNode();
			int index = getIndex(currentProject);
			if (index != -1) {
				projectStore.getProjectsList().remove(index);
				writeXML();
				generalTabPane.clearProject();
				statusBar.setText("Delete Project Ready");
			}
			if (index == 0) {
				this.jButtonOpenProject.setEnabled(false);
				this.jButtonDeleteProject.setEnabled(false);
				this.MenuItemOpen.setEnabled(false);
				this.MenuItemDelete.setEnabled(false);
			}
		}
     }
     
     private void saveProject() {
    	 
		int index;
		Project preProject = currentProject;
		generalTabPane.getInput(currentProject);

		Logic logic = new Logic();

		String message = logic.checkProject(projectStore, currentProject, preProject);

		if (message != null) {

			JOptionPane.showMessageDialog(this, message, "Warning",
					JOptionPane.WARNING_MESSAGE);

		} else {
			
			int n = JOptionPane.showConfirmDialog(this,
					"Would you like to save the changes", "Question",
					JOptionPane.YES_NO_OPTION);
			if (n == 0) {

				index = getIndex(preProject);
				if (index == -1) {
					projectStore.getProjectsList().add(currentProject);
					addObject(currentProject);
				} else {
					projectStore.getProjectsList().set(index, currentProject);
				}
				writeXML();
				statusBar.setText("Save project Ready");

				rootTreeNode.removeAllChildren();
				createNodes(rootTreeNode);
				treeModel.reload();
			}
		}

      }
      
      private void showProject(){
      	
      	generalTabPane.showProject();
      	
      }
      
      private void setModifyMode(boolean bEditable){
    	  
    	  generalTabPane.setModifyMode(bEditable);
      }
     
     private int getIndex(Project project){
    	 
    	 int index = -1;
    	 for (int i = 0; i < projectStore.getProjectsList().toArray().length; i++) {
    		 
    		 if(projectStore.getProjectsList().get(i).getProjectName().equals(project.getProjectName())){
    			 index = i;
    			 break;
    		 }
 		}
    	return index;
     }
     
    
    
    
     private void createNodes(DefaultMutableTreeNode top) {
     	
     	DefaultMutableTreeNode project = null;
     	for (int i = 0; i < projectStore.getProjectsList().toArray().length; i++){
 			project = new DefaultMutableTreeNode(projectStore.getProjectsList().get(i));
 			top.add(project);
 		}
     }
     
    

    /** Remove all nodes except the root node. */
    public void clear() {
        rootTreeNode.removeAllChildren();
        treeModel.reload();
    }

    /** Remove the currently selected node. */
    public void removeCurrentNode() {
        TreePath currentSelection = jTree.getSelectionPath();
        if (currentSelection != null) {
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                         (currentSelection.getLastPathComponent());
            MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
            if (parent != null) {
                treeModel.removeNodeFromParent(currentNode);
                return;
            }
        } 

    }
  
    //add new object to the tree
    public void addObject( Project project) {
        DefaultMutableTreeNode childNode = 
                new DefaultMutableTreeNode(project);

        treeModel.insertNodeInto(childNode, rootTreeNode, 
        		rootTreeNode.getChildCount());

        // Make sure the user can see the lovely new node.
        jTree.scrollPathToVisible(new TreePath(childNode.getPath()));
        
    }
    
    
       
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {
    	
        jToolBar = new javax.swing.JToolBar();
        jButtonOpenProject = new javax.swing.JButton();
        jButtonNewProject = new javax.swing.JButton();
        jButtonSaveProject = new javax.swing.JButton();
        jButtonDeleteProject = new javax.swing.JButton();
        jButtonCloseProject = new javax.swing.JButton();
        jSeparator5 = new javax.swing.JSeparator();
        jSplitPane = new javax.swing.JSplitPane();
        jTabbedPane = new javax.swing.JTabbedPane();
        statusBar = new javax.swing.JLabel();
        jMenuBar2 = new javax.swing.JMenuBar();
        MenuFile = new javax.swing.JMenu();
        MenuItemNew = new javax.swing.JMenuItem();
        MenuItemOpen = new javax.swing.JMenuItem();
        MenuItemDelete = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        MenuItemSave = new javax.swing.JMenuItem();
  //      MenuItemSaveAs = new javax.swing.JMenuItem();
  //      MenuItemExport = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        MenuItemExit = new javax.swing.JMenuItem();
        jSeparator6 = new javax.swing.JSeparator();
       
        MenuHelp = new javax.swing.JMenu();
        MenuItemAbout = new javax.swing.JMenuItem();
        
        
        rootTreeNode = new DefaultMutableTreeNode("Projects");
        treeModel = new DefaultTreeModel(rootTreeNode);
        treeModel.addTreeModelListener(new MyTreeModelListener());
        
        jTree = new javax.swing.JTree(treeModel);
      
        ((DefaultTreeCellRenderer)jTree.getCellRenderer()).setLeafIcon(new javax.swing.ImageIcon(getClass().getResource("/scrum/resource/class.gif")));
        jTree.setEditable(false);
        jTree.setRootVisible(false);
        jTree.setMinimumSize(new java.awt.Dimension(50, 400));
        jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        jTree.setShowsRootHandles(true);
       
        jTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
            	treeSelectionChanged(evt);
            }
        });
       
       

        setTitle("ScrumShark");
        setName("MainFrame");
       // setIconImage(new javax.swing.ImageIcon(getClass().getResource("/res/scrumSharkor.gif")).getImage());
        setForeground(java.awt.Color.white);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jToolBar.setFloatable(false);
        jButtonOpenProject.setIcon(new javax.swing.ImageIcon(getClass().getResource("/scrum/resource/open1.gif")));
        jButtonOpenProject.setText("Open");
        jButtonOpenProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toolBarOpenAction(evt);
            }
        });
        jToolBar.add(jButtonOpenProject);

        jButtonNewProject.setIcon(new javax.swing.ImageIcon(getClass().getResource("/scrum/resource/newfile1.gif")));
        jButtonNewProject.setText("New");
        jButtonNewProject.setName("");
        jButtonNewProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toolBarNewFileAction(evt);
            }
        });
        jToolBar.add(jButtonNewProject);

        jButtonSaveProject.setIcon(new javax.swing.ImageIcon(getClass().getResource("/scrum/resource/save1.gif")));
        jButtonSaveProject.setText("Save");
        jButtonSaveProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toolBarSaveAction(evt);
            }
        });
        jButtonSaveProject.setEnabled(false);
        jToolBar.add(jButtonSaveProject);

        jButtonDeleteProject.setIcon(new javax.swing.ImageIcon(getClass().getResource("/scrum/resource/close1.gif")));
        jButtonDeleteProject.setText("Delete");
        jButtonDeleteProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toolBarDeleteAction(evt);
            }
        });

        jToolBar.add(jButtonDeleteProject);
        
        

        jButtonCloseProject.setIcon(new javax.swing.ImageIcon(getClass().getResource("/scrum/resource/report1.gif")));
        jButtonCloseProject.setText("Close");
        jButtonCloseProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	toolBarCloseAction(evt);
            }
        });
        jButtonCloseProject.setEnabled(false);
        jToolBar.add(jButtonCloseProject);


        jToolBar.add(jSeparator5);

        getContentPane().add(jToolBar, java.awt.BorderLayout.NORTH);

        jSplitPane.setDividerLocation(100);
        jSplitPane.setSize(new Dimension(482, 27));
        jSplitPane.setOneTouchExpandable(true);
        jSplitPane.setAutoscrolls(true);
        
       

        jSplitPane.setLeftComponent(jTree);
        
        

        jTabbedPane.setMinimumSize(new java.awt.Dimension(400, 400));
        jTabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPane1StateChanged(evt);
            }
        });

        jSplitPane.setRightComponent(jTabbedPane);

        getContentPane().add(jSplitPane, java.awt.BorderLayout.CENTER);

        statusBar.setText(" ");
        statusBar.setBorder(new javax.swing.border.EtchedBorder(javax.swing.border.EtchedBorder.RAISED));
        getContentPane().add(statusBar, java.awt.BorderLayout.SOUTH);

        MenuFile.setMnemonic('F');
        MenuFile.setText("File");
        MenuItemNew.setMnemonic('N');
        MenuItemNew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        MenuItemNew.setText("New");
        MenuItemNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuItemNewActionPerformed(evt);
            }
        });

        MenuFile.add(MenuItemNew);

        MenuItemOpen.setMnemonic('O');
        MenuItemOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        MenuItemOpen.setText("Open");
        MenuItemOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuItemOpenActionPerformed(evt);
            }
        });

        MenuItemOpen.setEnabled(false);
        MenuFile.add(MenuItemOpen);

        MenuItemDelete.setText("Delete");
        MenuItemDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuItemDeleteActionPerformed(evt);
            }
        });
        MenuItemDelete.setEnabled(false);
        MenuFile.add(MenuItemDelete);

        MenuFile.add(jSeparator1);
        
        

        MenuItemSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        MenuItemSave.setMnemonic('S');
        MenuItemSave.setText("Save");
        MenuItemSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuItemSaveActionPerformed(evt);
            }
        });
        MenuItemSave.setEnabled(false);
        MenuFile.add(MenuItemSave);
        
        /*

        MenuItemSaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        MenuItemSaveAs.setMnemonic('A');
        MenuItemSaveAs.setText("Save As");
        MenuItemSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuItemSaveAsActionPerformed(evt);
            }
        });

        MenuFile.add(MenuItemSaveAs);

        MenuItemExport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        MenuItemExport.setMnemonic('X');
        MenuItemExport.setText("Export to XML");
        MenuItemExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuItemExportActionPerformed(evt);
            }
        });

        MenuFile.add(MenuItemExport);
        
        */

        MenuFile.add(jSeparator2);

        MenuItemExit.setMnemonic('x');
        MenuItemExit.setText("Exit");
        MenuItemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuItemExitActionPerformed(evt);
            }
        });

        MenuFile.add(MenuItemExit);
        MenuFile.add(jSeparator6);
        jMenuBar2.add(MenuFile);

     


        MenuHelp.setMnemonic('H');
        MenuHelp.setText("Help");
        MenuItemAbout.setText("About...");
        MenuItemAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuItemAboutActionPerformed(evt);
            }
        });

        MenuHelp.add(MenuItemAbout);
        jMenuBar2.add(MenuHelp);
        setJMenuBar(jMenuBar2);
        
        
       
        
        generalTabPane = new GeneralPane();
        jTabbedPane.addTab("General", new javax.swing.ImageIcon(getClass().getResource("/scrum/resource/general.gif")), generalTabPane);
      //  employeeTabPane = new EmployeePane();
       // jTabbedPane.addTab("Employee", new javax.swing.ImageIcon(getClass().getResource("/scrum/resource/constpool.gif")), employeeTabPane);
        
        pack();
        setSize(800, 600);
        setVisible(true);
    }
      
    
    
    private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {
        
       
    }
    
    
    
    //Selection Changed
    private void treeSelectionChanged(javax.swing.event.TreeSelectionEvent evt) {
    	
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
        							jTree.getLastSelectedPathComponent();
        
        if (node == rootTreeNode) return;
        if(node == null) return;
        Object nodeInfo = node.getUserObject();
        if(node.isLeaf()){
			
				currentProject = (Project) nodeInfo;
				generalTabPane.setCurrentProject(currentProject);
				showProject();
			
        }
    }
    
   
    
    private void MenuItemSaveActionPerformed(java.awt.event.ActionEvent evt) {
        saveProject();
    }
    
    private void toolBarSaveAction(java.awt.event.ActionEvent evt) {
        saveProject();
    }
    
    private void MenuItemDeleteActionPerformed(java.awt.event.ActionEvent evt) {
        deleteProject();
    }
    
    private void MenuItemOpenActionPerformed(java.awt.event.ActionEvent evt) {
    	
    	jButtonDeleteProject.setEnabled(false);
        jButtonNewProject.setEnabled(false);
        jButtonOpenProject.setEnabled(false);
        jButtonSaveProject.setEnabled(true);
        jButtonCloseProject.setEnabled(true);
        
        MenuItemDelete.setEnabled(false);
        MenuItemNew.setEnabled(false);
        MenuItemOpen.setEnabled(false);
        MenuItemSave.setEnabled(true);
    	
    	openProject();
    }
    
    private void toolBarOpenAction(java.awt.event.ActionEvent evt) {
        
        jButtonDeleteProject.setEnabled(false);
        jButtonNewProject.setEnabled(false);
        jButtonOpenProject.setEnabled(false);
        jButtonSaveProject.setEnabled(true);
        jButtonCloseProject.setEnabled(true);
        
        MenuItemDelete.setEnabled(false);
        MenuItemNew.setEnabled(false);
        MenuItemOpen.setEnabled(false);
        MenuItemSave.setEnabled(true);
      
        
        openProject();
    }
    
    private void toolBarDeleteAction(java.awt.event.ActionEvent evt) {
        deleteProject();
    }
    
    private void toolBarCloseAction(java.awt.event.ActionEvent evt) {
        
        jButtonDeleteProject.setEnabled(true);
        jButtonNewProject.setEnabled(true);
        jButtonOpenProject.setEnabled(true);
        jButtonSaveProject.setEnabled(false);
        jButtonCloseProject.setEnabled(false);
        
        MenuItemDelete.setEnabled(true);
        MenuItemNew.setEnabled(true);
        MenuItemOpen.setEnabled(true);
        MenuItemSave.setEnabled(false);
        
        closeProject();
    }
    
    //Tool Bar New Project
    private void toolBarNewFileAction(java.awt.event.ActionEvent evt) {
        
        jButtonDeleteProject.setEnabled(false);
        jButtonNewProject.setEnabled(false);
        jButtonOpenProject.setEnabled(false);
        jButtonSaveProject.setEnabled(true);
        jButtonCloseProject.setEnabled(true);
        
        MenuItemDelete.setEnabled(false);
        MenuItemNew.setEnabled(false);
        MenuItemOpen.setEnabled(false);
        MenuItemSave.setEnabled(true);
        createNewProject();
    }
    
    //Menu new project
    private void MenuItemNewActionPerformed(java.awt.event.ActionEvent evt) {
    	
    	 jButtonDeleteProject.setEnabled(false);
         jButtonNewProject.setEnabled(false);
         jButtonOpenProject.setEnabled(false);
         jButtonSaveProject.setEnabled(true);
         jButtonCloseProject.setEnabled(true);
         
         MenuItemDelete.setEnabled(false);
         MenuItemNew.setEnabled(false);
         MenuItemOpen.setEnabled(false);
         MenuItemSave.setEnabled(true);
        createNewProject();
    }
    
    //Exit Menu
    private void MenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {
        saveAndExit();
    }
    
    
    //Show About Dialog
    private void MenuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {
        AboutDialog dialog = new AboutDialog(this, false);
        dialog.setVisible(true);
    }
    
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        saveAndExit();
    }
    
    //Save and Exit
    private void saveAndExit() {
    	
    	int n = JOptionPane.showConfirmDialog(this,
				"Do you like to exit, you should check if changes has been saved", "Question",
				JOptionPane.YES_NO_OPTION);
    	
    	if(n == 0)
    		System.exit(0);
    }
    
    // Variables declaration 
    private javax.swing.JMenu MenuFile;
    private javax.swing.JMenu MenuHelp;
    private javax.swing.JMenuItem MenuItemAbout;
    private javax.swing.JMenuItem MenuItemDelete;
    private javax.swing.JMenuItem MenuItemExit;
    private javax.swing.JMenuItem MenuItemNew;
    private javax.swing.JMenuItem MenuItemOpen;
    private javax.swing.JMenuItem MenuItemSave;
    private javax.swing.JButton jButtonDeleteProject;
    private javax.swing.JButton jButtonNewProject;
    private javax.swing.JButton jButtonOpenProject;
    private javax.swing.JButton jButtonSaveProject;
    private javax.swing.JButton jButtonCloseProject;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JSeparator jSeparator6;
    private javax.swing.JSplitPane jSplitPane;  
    private javax.swing.JTabbedPane jTabbedPane;
    private javax.swing.JToolBar jToolBar;
    private javax.swing.JTree jTree;
    private javax.swing.JLabel statusBar;
    
}
